package com.buydeem.share.rabbit.mandatory;

import com.buydeem.share.rabbit.Utils;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

/**
 * mandatory 消息无法路由到队列
 *
 * @author zengchao
 * @date 2021-07-08 14:01:01
 */
@Slf4j
public class MandatoryDemo {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = Utils.getFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //创建Exchange
        channel.exchangeDeclare("mandatory.exchange", BuiltinExchangeType.DIRECT, true, false, new HashMap<>());
        //创建Queue
        channel.queueDeclare("mandatory.queue", true, false, false, new HashMap<>());
        //绑定路由
        channel.queueBind("mandatory.queue", "mandatory.exchange", "mandatory");

        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                log.error("replyCode = {},replyText ={},exchange={},routingKey={},body={}",replyCode,replyText,exchange,routingKey,new String(body));
            }
        });
        //设置mandatory = true
        //void basicPublish(String exchange, String routingKey, boolean mandatory, BasicProperties props, byte[] body)
        channel.basicPublish("mandatory.exchange", "mandatory-1",true, new AMQP.BasicProperties(), "测试mandatory的消息".getBytes(StandardCharsets.UTF_8));

    }
}
